<template>
  <div class="app">
    <div class="header-box">
      <van-icon name="arrow-left" size="24" @click="goBack" />
      <div class="header-item">
        {{ userInfo.regStatus == 4 ? "资料修改" : "商户入网" }}
      </div>
      <!-- <van-icon name="arrow-left"
                size="24"
      style="visibility: hidden;" />-->
      <span class="header-save" @click="noSave">保存</span>
    </div>
    <div class="content-box">
      <Remarks v-if="userInfo.regStatus == 4" :contents="userInfo.remarks" />
      <!-- 步骤条 -->
      <Steps
        v-if="T1"
        :dataSource="[
          { name: '1基本信息', checked: true },
          { name: '2结算信息' },
          { name: '3费率信息' },
          { name: '4附件信息' },
        ]"
      />
      <Steps
        v-else
        :dataSource="[
          { name: '1基本信息', checked: true },
          { name: '2附件信息' },
        ]"
      />
      <!-- 主体 -->
      <van-form validate-first input-align="right" ref="form">
        <van-field
          is-link
          readonly
          v-model="formData.openTypeText"
          label="开通类型"
          placeholder="请选择"
          @click="userInfo.regStatus == 4 ? () => {} : showPopup(1)"
          :disabled="userInfo.regStatus == 4"
        />
        <p class="notes">独立经营门店：支持分店有独立的结算账户</p>
        <p class="notes">直营连锁门店：与主店同一结算账户</p>
        <van-field
          v-if="T2"
          is-link
          readonly
          class="mt-margin"
          v-model="formData.merchantTypeText"
          label="商户类型"
          placeholder="请选择"
          @click="showPopup(2)"
        />
        <div class="attach-item" v-if="T3">
          <p class="attach-item-title">营业执照</p>
          <div class="upload-content">
            <div class="attach-label">
              <p>请上传营业执照正面图片</p>
              <p class="example" @click="lookExample(bizImgExample)">
                查看示例&nbsp;
                <van-icon name="arrow" />
              </p>
            </div>
            <van-uploader
              :after-read="uploadOpenImg"
              :before-delete="deleteOpenImg"
              v-model="bizImgList"
              :max-count="1"
              :multiple="false"
              @oversize="onOversize"
            >
              <img src="../../assets/store/biz-img.png" alt />
            </van-uploader>
          </div>
        </div>
        <van-field
          v-model="formData.merchantFullName"
          clearable
          class="mt-margin"
          label="商户全称"
          name="merchantFullName"
          placeholder="请输入商户全称"
          @input="change1"
          :rules="[
            {
              pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{1,50}$/,
              message: '请输入小于50的中文/字母/数字组合',
              trigger: 'onChange',
            },
            {
              validator: (val) => {
                if (formData.merchantType == 2 && val.includes('公司')) {
                  return false;
                } else {
                  return true;
                }
              },
              message: '企业执照不允许选择个体工商户类型入网！',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-model="formData.merchantAbbrName"
          clearable
          label="商户简称"
          name="merchantAbbrName"
          @input="change2"
          placeholder="请输入商户简称"
          :rules="[
            {
              pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{3,20}$/,
              message: '请输入3-20中文/字母/数字的商户简称',
              trigger: 'onChange',
            },
            {
              validator: (val) => {
                if (formData.merchantType == 2 && val.includes('公司')) {
                  return false;
                } else {
                  return true;
                }
              },
              message: '企业执照不允许选择个体工商户类型入网！',
              trigger: 'onChange',
            },
            {
              validator: asyncValidator,
              message: '该商户简称已存在，请重新输入',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-model="formData.person"
          clearable
          label="法人姓名"
          v-if="Number(formData.merchantType) !== 3"
          placeholder="请输入执照法人姓名"
          :rules="[
            {
              pattern: /^[\u4E00-\u9fa5a-zA-Z\uf900-\ufa2d·s]{1,35}$/,
              message: '请输入小于35的中文/字母组合',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-if="T4"
          v-model="formData.bizLicense"
          clearable
          label="执照编码"
          @input="change3"
          placeholder="请输入营业执照编码"
          :rules="[
            {
              pattern: /^[a-zA-Z0-9-_]{1,50}$/,
              message: '请输入小于50的字母/数字组合',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-if="T5"
          is-link
          readonly
          v-model="formData.bizStartTime"
          label="执照有效期"
          placeholder="执照开始日期"
          @click="showPopup(3)"
        />
        <van-field
          v-if="T6"
          is-link
          readonly
          v-model="formData.bizEndTime"
          label
          placeholder="执照结束日期"
          @click="showPopup(4)"
          :rules="[
            {
              validator: ValidateBizEndTime,
              message: '结束日期不能小于开始日期',
              trigger: 'onChange',
            },
          ]"
        />
        <!-- <van-field readonly
                   v-model="formData.bizAreaText"
                   :label="addressText"
                   :placeholder="addressPlaceholser"
                   @click="showPopup(7)"
                   >
          <template #input>
            <span>{{formData.bizAreaText}}</span>
            <span style="margin-left:10px;"><van-icon name="location" size="20" /></span>
            <span style="color:blue; font-size:12px;" @click="locationAddress">定位</span>
          </template>
        </van-field>-->
        <van-field
          readonly
          v-model="formData.bizAreaText"
          :label="addressText"
          :placeholder="addressPlaceholser"
          @click="showPopup(7)"
        />
        <van-field
          v-model="formData.merchantAddress"
          clearable
          label="详细地址"
          @input="change4"
          type="textarea"
          maxlength="255"
          show-word-limit
          placeholder="执照详细经营地址，精确到xx路xx号"
          :rules="[
            {
              pattern:
                /^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/,
              message: '请输入中文/数字/字母的详细地址',
              trigger: 'onChange',
            },
            {
              validator: (val) => {
                if (val.length < 6) {
                  return false;
                } else {
                  return true;
                }
              },
              message: '详细地址至少6个字符',
              trigger: 'onChange',
            },
          ]"
        />
        <van-field
          v-if="T7"
          class="mt-margin"
          label="经营范围"
          @input="change5"
          v-model="formData.bizScope"
          maxlength="200"
          placeholder="执照经营范围"
        ></van-field>
        <van-field
          v-if="T8"
          is-link
          class="mt-margin"
          @click="selectMcc"
          label="MCC"
          v-model="formData.mccText"
          placeholder="MCC"
        ></van-field>
        <div v-if="T9">
          <div class="attach-item">
            <p class="attach-item-title">法人身份证</p>
            <div class="upload-content">
              <div class="upload-item">
                <van-uploader
                  :after-read="uploadLegalIdCardFontImg"
                  :before-delete="deleteLegalFontImg"
                  v-model="legalIdCardFontImg"
                  :max-count="1"
                  @oversize="onOversize"
                >
                  <img src="../../assets/store/idCard-font.png" alt />
                </van-uploader>
                <p>请上传身份证人像面</p>
                <p class="example" @click="lookExample(idFontImgExample)">
                  查看示例&nbsp;
                  <van-icon name="arrow" />
                </p>
              </div>
              <div class="upload-item">
                <van-uploader
                  :after-read="uploadLegalIdCardBackImg"
                  :before-delete="deleteLegalBackImg"
                  v-model="legalIdCardBackImg"
                  :max-count="1"
                  @oversize="onOversize"
                >
                  <img src="../../assets/store/idCard-back.png" alt />
                </van-uploader>
                <p>请上传身份证国徽面</p>
                <p class="example" @click="lookExample(idBackImgExample)">
                  查看示例&nbsp;
                  <van-icon name="arrow" />
                </p>
              </div>
            </div>

            <div class="upload-content">
              <div class="upload-item">
                <van-uploader
                  :after-read="uploadLegalIdHandCardFontImg"
                  :before-delete="deleteLegalHandFontImg"
                  v-model="legalIdHandCardFontImg"
                  :max-count="1"
                  @oversize="onOversize"
                >
                  <img src="../../assets/store/idHand-font.png" alt />
                </van-uploader>
                <p>请上传法人手持身份证照</p>
                <p class="example" @click="lookExample(idHandFontImgExample)">
                  查看示例&nbsp;
                  <van-icon name="arrow" />
                </p>
              </div>
            </div>
          </div>
          <van-field
            class="mt-margin"
            v-model="formData.legalName"
            clearable
            label="法人姓名"
            @input="change6"
            placeholder="请输入法人身份证姓名"
            :rules="[
              {
                pattern: /^[\u4E00-\u9fa5a-zA-Z\uf900-\ufa2d·s]{1,35}$/,
                message: '请输入小于35的中文/字母组合',
                trigger: 'onChange',
              },
            ]"
          />
          <van-field
            v-model="formData.legalIdcard"
            clearable
            label="法人证件号"
            @input="change7"
            placeholder="请输入法人身份证号"
            @blur="handlePersonVerify"
            :rules="[
              {
                pattern: /^[0-9a-zA-Z]{1,18}$/,
                message: '请输入18位的数字/字母组合类型',
                trigger: 'onChange',
              },
            ]"
          />
          <van-field
            is-link
            readonly
            v-model="formData.legalStartTime"
            label="身份证有效期"
            placeholder="证件开始日期"
            @click="showPopup(5)"
          />
          <van-field
            is-link
            readonly
            v-model="formData.legalEndTime"
            label
            placeholder="证件结束日期"
            @click="showPopup(6)"
            :rules="[
              {
                validator: ValidateLegalEndTime,
                message: '结束日期不能小于开始日期',
                trigger: 'onChange',
              },
            ]"
          />
        </div>
        <van-field
          v-if="T9"
          v-model="formData.legalIdcardAddress"
          clearable
          label="法人身份证地址"
          @input="changeLegalIdcardAddress"
          type="textarea"
          maxlength="255"
          show-word-limit
          placeholder="请输入法人身份证地址"
          :rules="[
            {
              pattern:
                /^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/,
              message: '请输入中文/数字/字母的详细地址',
              trigger: 'onChange',
            },
            {
              validator: (val) => {
                if (val.length < 6) {
                  return false;
                } else {
                  return true;
                }
              },
              message: '详细地址至少6个字符',
              trigger: 'onChange',
            },
          ]"
        />
      </van-form>

      <!-- 以下是弹窗内容 -->
      <van-popup v-model="show1" position="bottom" :style="{ height: '40%' }">
        <van-picker
          title="开通类型"
          show-toolbar
          :columns="openTypies"
          @confirm="selectOpenTyepe"
          @cancel="onCancel(1)"
        />
      </van-popup>
      <van-popup v-model="show2" position="bottom" :style="{ height: '40%' }">
        <van-picker
          title="商户类型"
          show-toolbar
          :columns="merchantTypies"
          @confirm="selectMerchantType"
          @cancel="onCancel(2)"
        />
      </van-popup>
      <van-popup v-model="show3" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate1"
          type="date"
          title="执照开始日期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="selectTime1"
          @cancel="onCancel(3)"
        />
      </van-popup>
      <van-popup v-model="show4" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate2"
          type="date"
          title="执照结束日期"
          cancel-button-text="长期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="selectTime2"
          @cancel="longtTime1"
        />
      </van-popup>
      <van-popup v-model="show5" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate3"
          type="date"
          title="证件开始日期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="selectTime3"
          @cancel="onCancel(5)"
        />
      </van-popup>
      <van-popup v-model="show6" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-model="currentDate4"
          type="date"
          title="证件结束日期"
          cancel-button-text="长期"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="selectTime4"
          @cancel="longtTime2"
        />
      </van-popup>
      <van-popup v-model="show7" position="bottom" :style="{ height: '40%' }">
        <van-picker
          show-toolbar
          title="请选择地区"
          @change="onAreaChange"
          @cancel="onCancel(7)"
          @confirm="onAreaConfirm"
          :columns="areaColumns"
        />
      </van-popup>

      <van-dialog
        v-model="showExample"
        title="查看示例"
        confirmButtonText="关闭"
        confirmButtonColor="#FFB72F"
      >
        <img :src="exampleImg" class="example-img" />
      </van-dialog>
      <van-button
        block
        type="info"
        color="#FFB72F"
        :disabled="pass"
        @click="nextStep"
        class="next-step-btn"
        >下一步</van-button
      >
    </div>
  </div>
</template>

<script>
import bizImgExample from "../../assets/store/biz-img-example.png";
import idFontImgExample from "../../assets/store/idCard-font-example.png";
import idHandFontImgExample from "../../assets/store/idHand-font-example.png";
import idBackImgExample from "../../assets/store/idCard-back-example.png";
import { uploadImg, bizLicenseOcr, idCardOcr } from "@/api/upload";
import { getAreaData } from "@/api/area";
import { GMTToStr } from "@/utils/tools";
import { save } from "@/api/stores";
import {
  checkStoreAbbrName,
  getMerDetail,
  getCommonConfigByTenantId,
  storeCount,
  isBlacklist,
} from "@/api/merchant";
import { imgPreview, matchChinese } from "@/utils/utils.js";

export default {
  name: "Step1",
  components: {
    HeaderComp: () => import("@/components/HeaderComps"),
    Remarks: () => import("@/components/Remarks"),
    Steps: () => import("@/components/steps"),
  },
  data() {
    return {
      formData: {},
      minDate: new Date(1971, 0, 1),
      maxDate: new Date(2060, 10, 1),
      currentDate1: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate()
      ),
      currentDate2: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate()
      ),
      currentDate3: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate()
      ),
      currentDate4: new Date(
        new Date().getFullYear(),
        new Date().getMonth(),
        new Date().getDate()
      ),
      bizImgExample,
      idFontImgExample,
      idHandFontImgExample,
      idBackImgExample,
      exampleImg: "",
      showExample: false,
      validate: false,
      bizImgList: [],
      legalIdCardFontImg: [],
      legalIdCardBackImg: [],
      legalIdHandCardFontImg: [],
      openTypies: [
        {
          text: "直营连锁门店",
          value: "1",
        },
        {
          text: "独立经营门店",
          value: "2",
        },
      ],
      merchantTypies: [
        {
          text: "企业",
          value: "1",
        },
        {
          text: "个体",
          value: "2",
        },
        {
          text: "小微",
          value: "3",
          disabled:
            this.$store.state.user.agentInfo.xwStatus == 2 &&
            this.$store.state.merchant.payType == 2,
        },
      ],
      areaColumns: [
        {
          values: [],
          defaultIndex: 0,
        },
        {
          values: [],
          defaultIndex: 0,
        },
        {
          values: [],
          defaultIndex: 0,
        },
      ],
      show1: false,
      show2: false,
      show3: false,
      show4: false,
      show5: false,
      show6: false,
      show7: false,
      T1: true,
      T2: true,
      T3: true,
      T4: true,
      T5: true,
      T6: true,
      T7: true,
      T8: true,
      T9: true,
      T10: true,
      addressText: "执照省市",
      addressPlaceholser: "执照经营省份、城市、地区",
      firstSettleTypeListData: [],
    };
  },
  computed: {
    urlQuery() {
      return this.$store.state.user.urlQuery;
    },
    userInfo() {
      return this.$store.state.user.userInfo;
    },
    agentInfo() {
      return this.$store.state.user.agentInfo;
    },
    merchantForm() {
      return this.$store.state.merchant;
    },
    pass() {
      return this.$store.getters.valid_step1;
    },
  },
  watch: {
    formData: {
      handler(newV) {
        if (newV.openType == 1) {
          this.type2();
          this.$store.commit("setMerchantType", {
            text: "",
            value: "",
          });
        }
        if (newV.openType == 2) {
          this.type1();
          if (newV.merchantType == 1) {
            this.type3();
          } else if (newV.merchantType == 2) {
            this.type3();
          } else if (newV.merchantType == 3) {
            this.type5();
            let settlement = this.$store.state.settlement;
            if (settlement.acconutType != 2) {
              this.$store.commit("setAccountType", {
                text: "法人对私",
                value: "2",
              });
            }
          }
        }
      },
      deep: true,
    },
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == "/registers") {
      //   document.title = "返回APP";
      this.$dialog
        .confirm({
          title: "退出商户认证",
          message: `<div style="font-size:16px;line-height:12px;">
          <p>资料尚未完成，确认是否保存资料？</p>
           <p>已保存的资料可在认证页面继续填写</p></div>`,
          cancelButtonText: "不保存",
          cancelButtonColor: "#FFB72F",
          confirmButtonText: "保存资料",
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.$store.commit("setComplete", 0);
          this.$toast({
            type: "loading",
            message: "正在提交...",
            forbidClick: true,
            duration: 0,
          });
          save(this.$store.state)
            .then((res) => {
              if (res.code === 200) {
                document.title = "提交成功";
                this.$toast.clear();
              } else {
                this.$toast({
                  message: res.msg || "操作失败",
                  duration: 2000,
                  forbidClick: true,
                });
              }
            })
            .catch((err) => {
              this.$toast.clear();
              document.title = "返回APP";
            });
        })
        .catch(() => {
          // 取消
          document.title = "返回APP";
          // next();
        });
    } else {
      next();
    }
  },
  mounted() {
    let query = this.$route.query;
    if (query.token) {
      localStorage.setItem("fuhuibatoken", query.token);
    }
    console.log(query.storeId);
    if (query.storeId) {
      this.$store.dispatch("setStoreInfo", {
        id: query.storeId,
        tenantId: query.tenantId || "000001",
      });
      this.$router.replace({
        path: "/blank",
      });
    }
    if (this.merchantForm.bizImg) {
      this.bizImgList = [{ url: this.merchantForm.bizImg }];
    }
    if (this.merchantForm.legalFontImg) {
      this.legalIdCardFontImg = [
        {
          url: this.merchantForm.legalFontImg,
        },
      ];
    }
    if (this.merchantForm.legalHandFontImg) {
      this.legalIdHandCardFontImg = [
        {
          url: this.merchantForm.legalHandFontImg,
        },
      ];
    }
    if (this.merchantForm.legalBackImg) {
      this.legalIdCardBackImg = [
        {
          url: this.merchantForm.legalBackImg,
        },
      ];
    }
    this.getProvince("00");
    let form = this.$store.state.merchant;
    let newForm = JSON.parse(JSON.stringify(form));
    this.formData = newForm;
    if (this.formData.legalName && this.bizImgList.length) {
      if (!this.merchantForm.person) {
        this.formData.person = this.formData.legalName;
      }
    }
    window.scrollTo({
      left: 0,
      top: 0,
      behavior: "smooth",
    });
    if (this.userInfo.regApproach == "touristAdd") {
      this.openTypies = [
        {
          text: "商户",
          value: "3",
        },
        {
          text: "独立经营门店",
          value: "2",
        },
      ];
    } else {
      this.openTypies = [
        {
          text: "直营连锁门店",
          value: "1",
        },
        {
          text: "独立经营门店",
          value: "2",
        },
      ];
    }
    this.$nextTick(function () {
      if (this.userInfo.merchantId) {
        getMerDetail(this.userInfo.merchantId).then((res) => {
          if (res.data.defaultChannelCode) {
            this.$store.commit(
              "setDefaultChannelCode",
              res.data.defaultChannelCode
            );
          }
          this.defaultChannelCode = res.data.defaultChannelCode;
          if (res.data.merchantType == 3) {
            storeCount(this.userInfo.merchantId).then((s) => {
              getCommonConfigByTenantId().then((v) => {
                //   判断是否限制直营
                if (
                  v.data.microOpenDirectlyStoreFlag == 1 &&
                  v.data.microOpenDirectlyStoreNum <= s.data.fenleiTotal[1]
                ) {
                  this.openTypies = [
                    {
                      text: "独立经营门店",
                      value: "2",
                    },
                  ];
                }
                // 独立
                if (
                  v.data.merchantOpenStandStoreFlag == 1 &&
                  v.data.merchantOpenStandStoreNum <= s.data.fenleiTotal[2]
                ) {
                  this.openTypies = [
                    {
                      text: "直营连锁门店",
                      value: "1",
                    },
                  ];
                }
                if (
                  v.data.microOpenDirectlyStoreFlag == 1 &&
                  v.data.microOpenDirectlyStoreNum <= s.data.fenleiTotal[1] &&
                  v.data.merchantOpenStandStoreFlag == 1 &&
                  v.data.merchantOpenStandStoreNum <= s.data.fenleiTotal[2]
                ) {
                  this.openTypies = [
                    // {
                    //   text: "直营连锁门店",
                    //   value: "1",
                    // },
                    // {
                    //   text: "独立经营门店",
                    //   value: "2",
                    // },
                  ];
                }
              });
            });
          }
        });
      }
    });
    //
  },
  methods: {
    noSave() {
      const reg = /^[1-9]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[1,2][0-9]|3[0,1])$/;
      if (this.formData.openType == 2 || this.formData.openType == 3) {
        if (this.formData.merchantType != 3) {
          if (this.formData.bizStartTime) {
            if (!reg.test(this.formData.bizStartTime)) {
              this.$toast({
                message: "执照开始有效期格式不对，请重新选择",
                duration: 2000,
              });
              return false;
            }
            if (this.formData.bizEndTime != "88888888") {
              if (!reg.test(this.formData.bizEndTime)) {
                this.$toast({
                  message: "执照结束有效期格式不对，请重新选择",
                  duration: 2000,
                });
                return false;
              }
            }
          }
          if (this.formData.legalStartTime) {
            if (!reg.test(this.formData.legalStartTime)) {
              this.$toast({
                message: "身份证开始有效期格式不对，请重新选择",
                duration: 2000,
              });
              return false;
            }
            if (this.formData.legalEndTime != "88888888") {
              if (!reg.test(this.formData.legalEndTime)) {
                this.$toast({
                  message: "身份证结束有效期格式不对，请重新选择",
                  duration: 2000,
                });
                return false;
              }
            }
          }
        }
      }
      this.$dialog
        .confirm({
          title: "商户认证",
          message: `<div style="font-size:16px;line-height:12px;">
                <p>确认是否保存资料？</p> </div>`,
          cancelButtonText: "取消",
          // cancelButtonColor: "#FFB72F",
          confirmButtonText: "确认",
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          // 保存资料
          if (this.formData.openType) {
            this.$store.commit("setComplete", 0);
            this.$toast({
              type: "loading",
              message: "正在提交...",
              forbidClick: true,
              duration: 0,
            });
            save(this.$store.state)
              .then((res) => {
                // document.title = "提交成功";
                this.$toast.clear();
                if (res.code == 200) {
                  this.$toast({
                    type: "success",
                    message: "保存成功",
                    duration: 1500,
                  });
                  this.$store.dispatch("setSaved", true);
                } else {
                  this.$toast({
                    message: res.msg || "操作失败",
                    duration: 2000,
                    forbidClick: true,
                  });
                }
              })
              .catch((err) => {
                this.$toast.clear();
                // document.title = "返回APP";
              });
            // next();
          } else {
            document.title = "返回APP";
          }
        })
        .catch(() => {
          // 取消
          // document.title = "返回APP";
          // next();
        });
    },
    ValidateLegalEndTime(val) {
      let startUTC = new Date(this.formData.legalStartTime).getTime();
      let endtUTC = new Date(val).getTime();
      if (val == "88888888") {
        return true;
      } else if (startUTC > endtUTC) {
        this.$store.commit("setLegalStartEnd", "");
        return false;
      } else {
        return true;
      }
    },
    ValidateBizEndTime(val) {
      let startUTC = new Date(this.formData.bizStartTime).getTime();
      let endtUTC = new Date(val).getTime();
      if (val == "88888888") {
        return true;
      } else if (startUTC > endtUTC) {
        this.$store.commit("setBizStartEnd", "");
        return false;
      } else {
        return true;
      }
    },
    asyncValidator(val) {
      if (/^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{1,20}$/.test(val)) {
        return new Promise((resolve) => {
          checkStoreAbbrName({
            abbrName: val,
            storeNo: this.userInfo.storeNo,
            deptId: this.userInfo.deptId,
          })
            .then((res) => {
              resolve(res.success);
            })
            .catch((err) => {
              resolve(err.success);
            });
        });
      }
    },
    deleteOpenImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.bizImgList = [];
          this.$store.commit("PSetBizImg", "");
        });
    },
    deleteLegalFontImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.legalIdCardFontImg = [];
          this.$store.commit("PSetLegalFontImg", "");
        });
    },
    deleteLegalBackImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.legalIdCardBackImg = [];
          this.$store.commit("PSetLegalBackImg", "");
        });
    },
    change1(value) {
      if (
        !/^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{1,50}$/.test(value) ||
        (value.includes("公司") && this.formData.merchantType == 2)
      ) {
        this.$store.commit("ISetMerchantFullName", ""); //商户全称
      } else {
        this.$store.commit("ISetMerchantFullName", value); //商户全称
      }
    },
    change2(value) {
      if (
        !/^[\u4e00-\u9fa5a-zA-Z0-9\(\)\（\）]{1,20}$/.test(value) ||
        (value.includes("公司") && this.formData.merchantType == 2)
      ) {
        this.$store.commit("ISetMerchantAbbrName", ""); //商户简称
      } else {
        this.asyncValidator(value).then((res) => {
          if (res) {
            this.$store.commit("ISetMerchantAbbrName", value); //商户简称
          } else {
            this.$store.commit("ISetMerchantAbbrName", ""); //商户简称
          }
        });
      }
    },
    change3(value) {
      if (!/^[\u4e00-\u9fa5a-zA-Z0-9-_]{1,50}$/.test(value)) {
        this.$store.commit("ISetBizLicense", ""); //执照编码
      } else {
        this.$store.commit("ISetBizLicense", value); //执照编码
      }
    },
    change4(value) {
      if (
        !/^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/.test(
          value
        )
      ) {
        this.$store.commit("ISetMerchantAddress", ""); //详细地址
      } else {
        this.$store.commit("ISetMerchantAddress", value); //详细地址
      }
    },
    change5(value) {
      this.$store.commit("ISetBizScope", value); //经营范围
    },
    change6(value) {
      if (!/^[\u4E00-\u9fa5a-zA-Z\uf900-\ufa2d·s]{1,35}$/.test(value)) {
        this.$store.commit("ISetLegalName", ""); //法人姓名
      } else {
        this.$store.commit("ISetLegalName", value); //法人姓名
      }
    },
    change7(value) {
      if (!/^[0-9a-zA-Z]{1,18}$/.test(value)) {
        this.$store.commit("ISetLegalIdcard", ""); //法人证件号
      } else {
        this.$store.commit("ISetLegalIdcard", value); //法人证件号
      }
    },

    changeLegalIdcardAddress(value) {
      if (
        !/^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/.test(
          value
        )
      ) {
        this.$store.commit("ISetLegalIdcardAddress", ""); //法人身份证地址
      } else {
        this.$store.commit("ISetLegalIdcardAddress", value); //法人身份证地址
      }
    },
    getProvince(parentCode) {
      getAreaData(parentCode).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          let areaList = [];
          data.forEach((i) => {
            areaList.push({
              text: i.name,
              code: i.code,
              id: i.id,
            });
          });
          this.areaColumns[0].values = areaList;
          this.getCity(areaList[0].code);
        }
      });
    },
    getCity(parentCode) {
      getAreaData(parentCode).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          let areaList = [];
          data.forEach((i) => {
            areaList.push({
              text: i.name,
              code: i.code,
              id: i.id,
            });
          });
          this.areaColumns[1].values = areaList;
          this.getDistric(areaList[0].code);
        }
      });
    },
    getDistric(parentCode) {
      getAreaData(parentCode).then((res) => {
        if (res.code == 200) {
          let data = res.data;
          let areaList = [];
          data.forEach((i) => {
            areaList.push({
              text: i.name,
              code: i.code,
              id: i.id,
            });
          });
          this.areaColumns[2].values = areaList;
        }
      });
    },
    //当地区选择变化时
    onAreaChange(picker, values, index) {
      if (index == 0) {
        this.getCity(values[index].code);
      } else if (index == 1) {
        this.getDistric(values[index].code);
      }
    },
    //点击确定
    onAreaConfirm(value) {
      let province = "";
      let provinceId = "";
      let city = "";
      let cityId = "";
      let district = "";
      let districtId = "";

      if (value[2] && value[2].code) {
        district = value[2].text;
        districtId = value[2].id;
      }
      if (value[1] && value[1].code) {
        city = value[1].text;
        cityId = value[1].id;
      }
      if (value[0] && value[0].code) {
        province = value[0].text;
        provinceId = value[0].id;
      }
      this.$store.commit("setBizArea", {
        bizAreaId: [provinceId, cityId, districtId],
        bizAreaText: province + city + district,
      });
      this.formData.bizAreaText = province + city + district;
      this.show7 = false;
    },
    selectTime1(value) {
      this.formData.bizStartTime = GMTToStr(value);
      this.$store.commit("setBizStartTime", GMTToStr(value));
      this.show3 = false;
    },
    selectTime2(value) {
      this.formData.bizEndTime = GMTToStr(value);
      this.$store.commit("setBizStartEnd", GMTToStr(value));
      this.show4 = false;
    },
    longtTime1() {
      this.formData.bizEndTime = "88888888";
      this.$store.commit("setBizStartEnd", "88888888");
      this.show4 = false;
    },
    selectTime3(value) {
      this.formData.legalStartTime = GMTToStr(value);
      this.$store.commit("setLegalStartTime", GMTToStr(value));
      this.show5 = false;
    },
    selectTime4(value) {
      this.formData.legalEndTime = GMTToStr(value);
      this.$store.commit("setLegalStartEnd", GMTToStr(value));
      this.show6 = false;
    },
    longtTime2() {
      this.formData.legalEndTime = "88888888";
      this.$store.commit("setLegalStartEnd", "88888888");
      this.show6 = false;
    },
    selectMcc() {
      this.$router.push({
        path: "/mcc",
      });
    },
    locationAddress() {
      this.$router.push({
        path: "/locationAddress",
      });
    },
    lookExample(url) {
      this.exampleImg = url;
      this.showExample = true;
    },
    onOversize() {
      this.$toast("图片过大无法上传\n请上传10MB以内的图片！");
    },
    selectimg() {
      document.getElementById("file").value = "";
      this.$refs.file.change();
    },
    uploadOpenImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.bizImgList = [];
          this.$store.commit("PSetBizImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              let imgUrl = res.data.link;
              bizLicenseOcr(imgUrl)
                .then((result) => {
                  console.log("result", result);
                  file.status = "done";
                  this.change1(result.name);
                  this.change2(result.name);
                  this.change3(result.regNum);
                  this.change4(result.address);
                  this.change5(result.business);
                  // this.change6(result.person);
                  this.formData.person = result.person;
                  this.$store.commit("PSetPerson", result.person);
                  // let period1 = result.period.replace(/年/g, "/");
                  // let period2 = period1.replace(/月/g, "/");
                  // let period3 = period2.replace(/日/g, "");
                  // let period5 = period3.replace(/长期/g, "88888888");
                  const [bizStartTime, bizEndTime] = result.period.split("至");
                  this.$refs.form.validate("merchantFullName");
                  this.$refs.form.validate("merchantAbbrName");
                  this.formData.merchantFullName = result.name;
                  this.formData.merchantAbbrName = result.name;
                  this.formData.bizLicense = result.regNum;
                  this.formData.bizStartTime = matchChinese(bizStartTime, "/");
                  this.formData.bizEndTime = !matchChinese(bizEndTime, "")
                    ? "88888888"
                    : matchChinese(bizEndTime, "/");
                  this.formData.merchantAddress = result.address;
                  this.formData.bizScope = result.business;
                  this.$store.commit(
                    "setBizStartTime",
                    this.formData.bizStartTime
                  );
                  this.$store.commit(
                    "setBizStartEnd",
                    this.formData.bizEndTime
                  );
                  this.$store.commit("PSetBizImg", imgUrl);
                  this.bizImgList = [];
                  this.bizImgList.push({ url: imgUrl });
                })
                .catch((error) => {
                  file.status = "done";
                  this.$store.commit("PSetBizImg", imgUrl);
                  this.bizImgList = [];
                  this.bizImgList.push({ url: imgUrl });
                  //   file.message = "OCR识别失败";
                });
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    //法人手持身份证照
    uploadLegalIdHandCardFontImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.legalIdHandCardFontImg = [];
          this.$store.commit("PSetLegalHandFontImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              let imgUrl = res.data.link;
              this.$store.commit("PSetLegalHandFontImg", imgUrl);
              this.legalIdHandCardFontImg = [];
              this.legalIdHandCardFontImg.push({
                url: imgUrl,
              });
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    deleteLegalHandFontImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.legalIdHandCardFontImg = [];
          this.$store.commit("PSetLegalHandFontImg", "");
        });
    },

    uploadLegalIdCardFontImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.legalIdCardFontImg = [];
          this.$store.commit("PSetLegalFontImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              let imgUrl = res.data.link;
              idCardOcr(imgUrl)
                .then((result) => {
                  if (!result.nation) {
                    file.status = "done";
                    // file.message = "OCR识别失败";
                    this.$store.commit("PSetLegalFontImg", imgUrl);
                    this.legalIdCardFontImg = [];
                    this.legalIdCardFontImg.push({
                      url: imgUrl,
                    });
                  } else {
                    file.status = "done";
                    this.change6(result.name);
                    this.change7(result.idNum);
                    this.formData.legalName = result.name;
                    this.formData.legalIdcard = result.idNum;
                    // 获取法人身份证地址
                    this.formData.legalIdcardAddress = result.address;
                    this.$store.commit(
                      "ISetLegalIdcardAddress",
                      result.address
                    );
                    this.$store.commit("PSetLegalFontImg", imgUrl);
                    this.legalIdCardFontImg = [];
                    this.legalIdCardFontImg.push({
                      url: imgUrl,
                    });
                  }
                })
                .catch((error) => {
                  file.status = "done";
                  //   file.message = "OCR识别失败";
                  this.$store.commit("PSetLegalFontImg", imgUrl);
                  this.legalIdCardFontImg = [];
                  this.legalIdCardFontImg.push({
                    url: imgUrl,
                  });
                });
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    uploadLegalIdCardBackImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.legalIdCardBackImg = [];
          this.$store.commit("PSetLegalBackImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              let imgUrl = res.data.link;
              idCardOcr(imgUrl)
                .then((result) => {
                  if (result.nation) {
                    file.status = "done";
                    // file.message = "OCR识别失败";
                    this.$store.commit("PSetLegalBackImg", imgUrl);
                    this.legalIdCardBackImg = [];
                    this.legalIdCardBackImg.push({
                      url: imgUrl,
                    });
                  } else {
                    file.status = "done";
                    let arr = result.validDate.split("-");
                    let start = arr[0].replace(/\./g, "/");
                    let end =
                      arr[1] == "长期"
                        ? "88888888"
                        : arr[1].replace(/\./g, "/");
                    this.formData.legalStartTime = start;
                    this.formData.legalEndTime = end;
                    this.$store.commit("setLegalStartTime", start);
                    this.$store.commit("setLegalStartEnd", end);
                    this.$store.commit("PSetLegalBackImg", imgUrl);
                    this.legalIdCardBackImg = [];
                    this.legalIdCardBackImg.push({
                      url: imgUrl,
                    });
                  }
                })
                .catch((error) => {
                  file.status = "done";
                  //   file.message = "OCR识别失败";
                  this.$store.commit("PSetLegalBackImg", imgUrl);
                  this.legalIdCardBackImg = [];
                  this.legalIdCardBackImg.push({
                    url: imgUrl,
                  });
                });
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    goBack() {
      if (this.$store.state.common.Saved) {
        document.title = "返回APP";
      } else {
        this.$router.push({
          path: "/registers",
        });
      }
    },
    selectOpenTyepe(data, index) {
      this.formData.openTypeText = data.text;
      this.formData.openType = data.value;
      this.$store.commit("setOpenType", data);
      this.show1 = false;
    },
    selectMerchantType(data, index) {
      this.formData.merchantTypeText = data.text;
      this.formData.merchantType = data.value;
      this.$store.commit("setMerchantType", data);
      this.show2 = false;
    },
    onCancel(e) {
      this[`show${e}`] = false;
    },
    showPopup(e) {
      if (e == 4 && !this.formData.bizStartTime) {
        this.$toast("请先选择开始日期");
        return false;
      }
      if (e == 6 && !this.formData.legalStartTime) {
        this.$toast("请先选择开始日期");
        return false;
      }
      this[`show${e}`] = true;
    },
    nextStep() {
      const reg = /^[1-9]\d{3}\/(0[1-9]|1[0-2])\/(0[1-9]|[1,2][0-9]|3[0,1])$/;
      if (this.formData.openType == 2 || this.formData.openType == 3) {
        if (this.formData.merchantType != 3) {
          if (!reg.test(this.formData.bizStartTime)) {
            this.$toast({
              message: "执照开始有效期格式不对，请重新选择",
              duration: 2000,
            });
            return false;
          }
          if (this.formData.bizEndTime != "88888888") {
            if (!reg.test(this.formData.bizEndTime)) {
              this.$toast({
                message: "执照结束有效期格式不对，请重新选择",
                duration: 2000,
              });
              return false;
            }
          }
          if (!reg.test(this.formData.legalStartTime)) {
            this.$toast({
              message: "身份证开始有效期格式不对，请重新选择",
              duration: 2000,
            });
            return false;
          }
          if (this.formData.legalEndTime != "88888888") {
            if (!reg.test(this.formData.legalEndTime)) {
              this.$toast({
                message: "身份证结束有效期格式不对，请重新选择",
                duration: 2000,
              });
              return false;
            }
          }

          if (this.formData.person !== this.formData.legalName) {
            this.$toast({
              message: "营业执照法人姓名与法人身份证姓名不一致",
              duration: 2000,
            });
            return false;
          }
        }
      }
      if (this.T9) {
        const reg =
          /^[\u4e00-\u9fa5a-zA-Z0-9\-\_\（\）\(\)\s\:\：.。,，\#\——]{1,255}$/;
        if (!reg.test(this.formData.legalIdcardAddress)) {
          this.$toast({
            message: "请输入中文/数字/字母的法人身份证地址",
            duration: 2000,
          });
          return false;
        }
        if (this.formData.legalIdcardAddress.length < 6) {
          this.$toast({
            message: "法人身份证地址至少6个字符",
            duration: 2000,
          });
          return false;
        }
      }
      this.$store.commit("getLangLatitude");
      this.$store.dispatch("getSystemRates");
      this.$store.dispatch("getUperAgentRates", this.agentInfo.id);
      if (this.formData.openType == 1) {
        this.$router.push({
          path: "/step4",
        });
      } else {
        this.$router.push({
          path: "/step2",
        });
      }
    },
    // 以下是联动展示控制部分
    // 1：独立经营门店
    type1() {
      this.addressText = "执照省市";
      this.addressPlaceholser = "执照经营省份、城市、地区";
      this.T1 = true;
      this.T2 = true;
      this.T3 = true;
      this.T4 = true;
      this.T5 = true;
      this.T6 = true;
      this.T7 = true;
      this.T8 = true;
      this.T9 = true;
    },
    // 1：直营连锁门店
    type2() {
      this.addressText = "经营省市区";
      this.addressPlaceholser = "请输入营业所在省份、城市、区";
      this.T1 = false;
      this.T2 = false;
      this.T3 = false;
      this.T4 = false;
      this.T5 = false;
      this.T6 = false;
      this.T7 = false;
      this.T8 = false;
      this.T9 = false;
    },
    //企业
    type3() {
      this.addressText = "执照省市";
      this.addressPlaceholser = "执照经营省份、城市、地区";
      this.T3 = true;
      this.T4 = true;
      this.T5 = true;
      this.T6 = true;
      this.T9 = true;
    },
    // 个体
    type4() {},
    // 小微
    type5() {
      this.addressText = "经营省市";
      this.addressPlaceholser = "请输入营业所在省份、城市、区";
      this.T3 = false;
      this.T4 = false;
      this.T5 = false;
      this.T6 = false;
      this.T9 = false;
    },
    handlePersonVerify() {
      if (
        /^[0-9a-zA-Z]{1,18}$/.test(this.formData.legalIdcard) &&
        this.formData.legalIdcard.length == 18
      ) {
        isBlacklist(this.formData.legalIdcard).then(({ data }) => {
          if (data.isBlacklist) {
            let msg = data.consumerHotline
              ? `法人身份证号填写失败，代码1000，请联系客服${data.consumerHotline}`
              : `法人身份证号填写失败，代码1000`;
            this.$toast(msg);
          }
        });
      }
    },
  },
};
</script>
<style scoped lang="less">
.content-box {
  min-height: 740px;
}
/deep/.van-picker-column__item--selected {
  color: #ff9600 !important;
}
/deep/.van-picker__confirm {
  color: #ff9600 !important;
}
/deep/.van-field__label {
  color: #323233;
}
/deep/.van-dialog__content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 57px 0;
}
/deep/.van-uploader {
  width: 334px;
  height: 224px;
}
/deep/.van-uploader__wrapper {
  width: 334px;
  height: 224px;
}
/deep/.van-uploader__preview-image {
  width: 334px;
  height: 224px;
}
/deep/.van-uploader__preview {
  width: 334px;
  height: 224px;
}
img {
  width: 334px;
  height: 224px;
}
.next-step-btn {
  width: 80%;
  margin: 100px auto;
}
.app {
  background: #f9f9f9;
  height: 100%;
}
.content-box {
  background: #f9f9f9;
  padding-bottom: 1px;
  margin-top: 110px;
  box-sizing: border-box;
}

.mt-margin {
  margin-top: 24px;
}
.example-img {
  width: 420px;
  height: 270px;
}
.attach-item {
  margin-top: 24px;
  background: #fff;
  padding: 35px 32px;
  p.attach-item-title {
    font-size: 30px;
    font-weight: 400;
    color: #131313;
  }

  .upload-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .attach-label {
      width: 45%;
      padding-left: 5px;
    }
    .upload-item {
      margin-top: 20px;
    }
    p {
      font-size: 28px;
      font-weight: 400;
      color: #131313;
      margin: 12px 0;
      text-align: center;
      opacity: 0.8;
    }
    .example {
      display: flex;
      align-items: center;
      color: #ffb72f;
      justify-content: center;
    }
  }
}
.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px;
  border-bottom: 1px solid #d7d7d7;
  font-size: 36px;
  background: #fff;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 99;
  .header-item {
    font-weight: 500;
    color: #131313;
  }
  .header-save {
    color: #ffb72f;
    font-size: 28px;
  }
}
.notes {
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  opacity: 0.7;
  padding: 24px 35px 0;
  line-height: 35px;
}
</style>
